package ps.server.net;

import java.io.ByteArrayOutputStream;
import java.util.LinkedList;

import ps.net.Packet;


public class PacketSender extends Thread {
    
    private boolean running = true;
    
    private LinkedList<Packet> packetList = new LinkedList<Packet>();
    
    private ByteArrayOutputStream buffer = new ByteArrayOutputStream(16 * 1024);
    
    boolean queueEmpty = true;
    
    public PacketSender() {
        start();
    }
    
    public void stopPacketSender() {
        running = false;
    }
    
    public void waitForEmptyQueue() {
        while (!queueEmpty) {
            try {
                yield();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    
    @Override
    public void run() {
        while (running) {
            try {
                Packet packet = null;
                synchronized (packetList) {
                    packet = packetList.poll();
                }
                
                if (packet != null) {
                    
                    buffer.reset();
                    packet.writePacket(buffer);
                    
                    for (ClientInfo clientInfo : packet.getReciever()) {
                        clientInfo.send(buffer);
                        yield();
                        
//                        System.out.println("SEND: " + packet);
                        
                        if (packet.isTypeOf(Packet.TYPE_CLIENT_INFO)) {
                            clientInfo.setLastClientInfoSent(System.currentTimeMillis());
                        }
                    }
                } else {
                    queueEmpty = true;
                    sleep(1);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    
    public void send(Packet packet) {
        queueEmpty = false;
        synchronized (packetList) {
            packetList.add(packet);
        }
//        waitForEmptyQueue();
    }
    
}
